package cn.xiqi.cms.oper;

import java.util.ArrayList;
import java.util.List;

import cn.xiqi.cms.hibernate.DAO.DataDAOImpl;
import cn.xiqi.cms.hibernate.beans.Metadata;
import cn.xiqi.cms.hibernate.service.DataService;
import cn.xiqi.cms.hibernate.service.DataServiceImpl;

public class MetaOper {
	private DataService service;
	
	public MetaOper(){
		service = new DataServiceImpl();
		service.setDao(new DataDAOImpl());
	}
	
	public List<String> cateList(){
		List<String> metas;
		
		metas = service.getCate();
		return metas;
	}
	
	public List<Metadata> metaList(String cate){
		List<Metadata> metas;
		List<Metadata> data = new ArrayList<>();
		
		metas = service.getByCate(cate);
		for(Metadata meta:metas){
			if(meta.getKey() != null){
				data.add(meta);
			}
		}
		return data;
	}
	
	public boolean addData(String cate, String key, int value){
		boolean b = true;
		
		try{
			service.addValue(cate, key, value);
		}catch(Exception e){
			b = false;
		}
		return b;
	}
	
	public boolean updateData(int dataID, String key, int value){
		boolean b = true;
		Metadata record;
		
		try{
			record = service.getByID(dataID);
			record.setKey(key);
			record.setValue(value);
			service.update(record);
		}catch(Exception e){
			b = false;
		}
		return b;
	}
	
	public boolean deleteData(Integer dataID, String cate){
		boolean b = false;
		List<Metadata> records;
		Metadata record;
		
		records = service.getByCate(cate);
		record = service.getByID(dataID);
		if(records.size()==1){
			record.setKey(null);
			record.setValue(0);
			b = service.update(record);
		}
		else{
			b = service.delete(record);
		}
		return b;
	}
	
	public boolean addCate(String cateName){
		boolean b = true;
		
		try{
			service.addCate(cateName);
		}catch(Exception e){
			b = false;
		}
		return b;
	}
	
	public boolean deleteCate(String cateName){
		boolean b = true;
		List<Metadata> metas;
		
		metas = service.getByCate(cateName);
		for(Metadata meta:metas){
			b = b && service.delete(meta);
		}
		return b;
	}
	
	public boolean editCate(String oldName, String newName){
		boolean b = true;
		List<Metadata> metas;
		
		metas = service.getByCate(oldName);
		for(Metadata meta:metas){
			meta.setCate(newName);
			b = b && service.update(meta);
		}
		return b;
	}
	
	public boolean isDataUnique(String cate, int value){
		boolean b = true;
		List<Metadata> records;
		
		records = service.getByCate(cate);
		for(Metadata record:records){
			if(record.getValue() == value && record.getKey() != null){
				b = false;
			}
		}
		return b;
	}
	
	public boolean isCateExist(String cate){
		boolean b = true;
		List<Metadata> records;
		
		records = service.getByCate(cate);
		b = !records.isEmpty();
		return b;
	}
	
	public Metadata getByID(int id){
		Metadata meta;
		
		meta = service.getByID(id);
		return meta;
	}
}
